<template>
  <div class="putAshGtoud">
    <div class="cm-header">
      <el-input v-model="groupName" style="width: 500px">
        <template slot="prepend">分组名称：</template>
      </el-input>
      <p>分组名称即docx文件名称，文件名请正规化(ps: 可以选择下面的对面API进行特别导出)</p>
      <el-button type="primary" style="width: 500px" @click="exportApi">导出docx文档</el-button>
      <p>Eolink根节点API分组名称 (ps:该导出是对接eolinker的，导出的json文件可以直接导入eolinker进行接口维护，分组名称是根节点的名称)</p>
      <el-button type="info" style="width: 500px" @click="exportEolinkApi">导出JSON</el-button>
    </div>
    <el-divider />
    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="changeIndeterminate">全选</el-checkbox>
    <el-tree
      ref="tree"
      :default-expand-all="true"
      :data="list"
      show-checkbox
      node-key="id"
      :props="defaultProps"
      @check="handleNodeClick"
    />
  </div>
</template>

<script>
import { exportDocApi, exportEolinkApi, getApiV2, getErrorStatusList } from '@/api/api'
import { getType } from '@/utils/typeUtil'
import { getRequestType } from '@/utils/requestType'
import FileSaver from 'file-saver'
import { formatDate } from '@/utils/dateUtil'
import ErrorAssert from '@/utils/error/ErrorAssert'
import { exportDocx } from '@/utils/docUtil'

export default {
  name: 'Index',
  data() {
    return {
      isIndeterminate: false,
      checkAll: [],
      checkList: [],
      idList: [],
      list: [],
      groupName: '我的分组api',
      errorStatusList: [],
      defaultProps: {
        children: 'apiList',
        label: 'apiName'
      }
    }
  },
  mounted() {
    this.getApi()
  },
  methods: {
    handleNodeClick() {
      const checkedNodes = this.$refs.tree.getCheckedKeys()
      if (checkedNodes.length === 0) {
        this.isIndeterminate = false
        this.checkAll = []
      } else {
        this.isIndeterminate = true
      }
    },
    changeIndeterminate() {
      const checkedNodes = this.$refs.tree.getCheckedKeys()
      if (checkedNodes.length === this.idList.length) {
        this.$refs.tree.setCheckedKeys([])
        this.isIndeterminate = false
        this.checkAll = []
      } else {
        this.$refs.tree.setCheckedKeys(this.idList)
        this.isIndeterminate = true
      }
    },
    getApi() {
      getApiV2().then((res) => {
        const { code, data } = res.data
        if (code === 0) {
          this.list = JSON.parse(JSON.stringify(data.apiModel))
          this.idList = JSON.parse(JSON.stringify(data.idList))
          this.$refs.tree.setCheckedKeys(this.idList)
          this.isIndeterminate = data.length !== 0
        }
      })
    },
    exportApi() {
      const parentArr = this.$refs.tree.getHalfCheckedKeys()
      const checkedNodeKeys = this.$refs.tree.getCheckedKeys()
      ErrorAssert.isEmptyArray(checkedNodeKeys, '导出选项不能为空，请选择下面API节点')
      const data = {
        groupName: this.groupName,
        idList: checkedNodeKeys.concat(parentArr)
      }
      exportDocApi(data).then((res) => {
        const { code, data } = res.data
        if (code === 0 && data.length !== 0) {
          const date = new Date()
          const dt = formatDate(date, 'yyyyMMddhhmmss')
          exportDocx('./api.docx', { list: data }, `swagger_api_${this.groupName}_${dt}.docx`)
          this.$message.success('操作成功')
        }
      })
    },
    exportEolinkApi() {
      const parentArr = this.$refs.tree.getHalfCheckedKeys()
      const checkedNodeKeys = this.$refs.tree.getCheckedKeys()
      ErrorAssert.isEmptyArray(checkedNodeKeys, '导出选项不能为空，请选择下面API节点')
      const data = {
        groupName: this.groupName,
        idList: checkedNodeKeys.concat(parentArr)
      }
      exportEolinkApi(data).then((res) => {
        const { code, data } = res.data
        if (code === 0) {
          if (data !== null && data.length !== 0) {
            // 将json转换成字符串
            const jsonData = JSON.stringify(data)
            const blob = new Blob([jsonData], { type: '' })
            const date = new Date()
            const dt = formatDate(date, 'yyyyMMddhhmmss')
            // const textStr = 'aaaaa,bbbbbbb,cccccc'
            FileSaver.saveAs(blob, `swagger_api_${dt}.json`)
            this.$message.success('操作成功')
          } else {
            this.$message.error('没有找到相关api，无法生成文件')
          }
        }
      })
    },
    getErrorStatusList() {
      getErrorStatusList().then((res) => {
        const { data } = res
        if (data.code === 0) {
          this.errorStatusList = JSON.parse(JSON.stringify(data.data))
        }
      })
    },
    setParam(params) {
      if (params != null) {
        params.forEach(param => {
          param.array = param.array ? 'array' : ''
          param.dataType = this.getType(param.dataType)
          if (param.children != null) {
            this.setParam(param.children)
          }
        })
      }
    },
    getType(str) {
      return getType(str)
    },
    getRequestType(str, method) {
      if (method === 'GET') {
        return 'application/www-form-urlencoded'
      }
      return getRequestType(str)
    }
  }
}
</script>

<style scoped>
.putAshGtoud {
  padding: 8px 12px;
  margin: 16px 0;
  /*color: #00bfff;*/
}

.cm-header {
  margin: auto 0;
  display: flex;
  flex-direction: column;
}

.level1Menu {
  border: 0.1px solid #9ea7b4;
  padding: 10px;
  margin: 10px;
}

.level1MenuHead {
  padding: 10px 24px;
  background: #f7f7f7;
  font-size: 30px;
  border-bottom: 1px solid #d8d8d8;
  margin-bottom: 15px;
}

.level1MenuChildren {
  padding: 10px 50px;
}
</style>
